package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerQuickStart {
    public static void main(String[] args) {
        Properties props = new Properties();

        //1.kafka配置信息
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.86.128:9092");
        //kay value 反序列化
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //消费者组
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "group2");

        //2.创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

        //3.订阅主题
        //consumer.subscribe(Collections.singletonList("topic-first"));
        consumer.subscribe(Collections.singletonList("itcast-topic-out"));

        //当前线程一直处于监听状态
//        while (true) {
//            //4.拉取信息
//            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
//            for (ConsumerRecord<String, String> record : records) {
//                System.out.println("key = " + record.key());
//                System.out.println("value = " + record.value());
//            }
//        }
       try{
           while (true) {
               //4.拉取信息
               ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
               for (ConsumerRecord<String, String> record : records) {
                   System.out.println("key = " + record.key());
                   System.out.println("value = " + record.value());
                   System.out.println("partition = " + record.partition());
                   System.out.println("offset = " + record.offset());
               }
               //异步提交偏移量
               consumer.commitAsync();
           }
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("错误信息:"+e);
       }
       finally {
           //同步提交偏移量
           consumer.commitSync();
           consumer.close();
       }


    }
}
